package cn.summit.core.mobile;

import cn.summit.core.authentication.handler.CustomfailureHandler;
import cn.summit.core.authentication.MyConstant;
import cn.summit.core.authentication.exception.CustomValidException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义手机验证码
 *
 * @author summit
 * @since 2020/3/4 21:54
 */
@Component
public class MobileValidateFilter extends OncePerRequestFilter {


    @Autowired
    private CustomfailureHandler customfailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
        // 1. 判断 请求是否为手机登录，且post请求
        if ("/mobile/form".equals(request.getRequestURI()) && "post"
            .equalsIgnoreCase(request.getMethod())) {
            try {
                // 校验验证码合法性
                validate(request);
                validate(request);
            } catch (AuthenticationException e) {
                // 交给失败处理器进行处理异常
                customfailureHandler.onAuthenticationFailure(request, response, e);
                // 一定要记得结束
                return;
            }
        }

        // 放行
        filterChain.doFilter(request, response);
    }

    private void validate(HttpServletRequest request) {
        // 先获取seesion中的验证码
        String sessionCode = (String) request.getSession()
            .getAttribute(MyConstant.SESSION_KEY_MOBILE_CODE);
        // 获取用户输入的验证码
        String inpuCode = request.getParameter("code");
        // 判断是否正确
        if (StringUtils.isBlank(inpuCode)) {
            throw new CustomValidException("验证码不能为空");
        }

        if (!inpuCode.equalsIgnoreCase(sessionCode)) {
            throw new CustomValidException("验证码输入错误");
        }
    }
}
